package rentcar.web;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import rentcar.domain.Car;
import rentcar.service.CarService;


@Controller
@RequestMapping("/car")
public class CarController {

	@Autowired
	private CarService carService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView listClients() {

		ModelAndView mav = new ModelAndView();
		mav.addObject("cars", carService.getCars());
		mav.setViewName("car.list");
		return mav;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String showCarProfile(
			@PathVariable("id") Car car,
			HttpSession session, Model model) {

		model.addAttribute("car", car);
		
		return "car.details";
	}	
	
	
	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public ModelAndView newCarForm(Model model) {

		model.addAttribute("car", new Car(0L, "Марка автомобиля", "Гос.номер", "Цвет", "Цена 1 суток аренды"));
		model.addAttribute("action", "new");

		ModelAndView mav = new ModelAndView();
		mav.setViewName("car.form");
		return mav;
	}	

	@RequestMapping(value = "/new", method = RequestMethod.POST)
	public String newCarSubmit(
			@ModelAttribute Car car, 
			Model model) {
		
		if (car != null) {
			carService.saveCar(car);			
			model.addAttribute("cars", carService.getCars());
		}
		model.asMap().remove("car");
		return "car.list";
	}	
	

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String editCarForm(
			@PathVariable("id") Car car,
			HttpSession session, Model model) {

		model.addAttribute("car", car);
		return "car.form.edit";
	}	

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String editCarSubmit(
			@ModelAttribute Car car, 
			Model model) {
		
		if (car != null) {
			//System.out.println("active:" + client.isActive());
			carService.updateCar(car);			
			model.addAttribute("cars", carService.getCars());
		}
		
		model.asMap().remove("car");
		return "car.list";
	}
	
	
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String deleteCar(
			@PathVariable("id") Car car,
			HttpSession session, Model model) {
		
		carService.deleteCar(car);			
		model.addAttribute("cars", carService.getCars());
		
		return "car.list";
	}
	
	
	
}
